import axios from "axios";
import type { AxiosRequestConfig, AxiosResponse, AxiosError } from "axios";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

// 创建 axios 实例
const axiosInstance = axios.create({
  timeout: 10000,
  headers: {
    "Content-Type": "application/json",
  },
});

// 请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    // 只在浏览器环境中尝试获取 token
    if (typeof window !== "undefined") {
      const token =
        localStorage.getItem("token") || localStorage.getItem("access_token");
      if (token) {
        if (config.headers) {
          config.headers.Authorization = `Bearer ${token}`;
        }
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => {
    const { status, data } = response;
    if (status === 200) {
      return data;
    } else if (status === 401) {
      return Promise.reject(new Error("登录已失效"));
    } else {
      return Promise.reject(new Error("请求失败"));
    }
  },
  (error: AxiosError) => {
    ElMessage.error("请求失败");
    return Promise.reject(error);
  }
);

interface RequestOptions {
  method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
  data?: object;
  params?: object;
  headers?: Record<string, string>;
}

export async function request<T>(
  endpoint: string,
  options: RequestOptions = {}
): Promise<T> {
  const { method = "GET", data, params, headers = {} } = options;

  // 在每次请求时动态获取 baseURL
  const runtimeConfig = useRuntimeConfig();
  const baseURL = runtimeConfig.public?.apiBase || "";

  const axiosConfig: AxiosRequestConfig = {
    baseURL,
    url: endpoint,
    method,
    headers,
    params,
    data,
  };

  try {
    const response = await axiosInstance(axiosConfig);
    return response as T;
  } catch (error) {
    throw error;
  }
}
